package 数据结构.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        System.out.println("前序排列");
        priOrder(root);
    }

    public static void priOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("是空树");
        }
    }

    public static Node createHuffmanTree(int[] arr) {
        List<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }

        // System.out.println(nodes);
        while (nodes.size() > 1) {
            //排序
            Collections.sort(nodes);
            //1.取出权值最小的节点(最小的单个节点)
            Node leftNode = nodes.get(0);
            //2.取出第二小的节点
            Node rightNode = nodes.get(1);
            //3.创建一颗新的二叉树
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            //4.删除处理过的二叉树
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            //5.将parent键入nodes
            nodes.add(parent);
            System.out.println(nodes);
        }

        return nodes.get(0);
    }


}

class Node implements Comparable<Node> {


    int value;//节点权值
    Node left;//指向左子节点
    Node right;//右子节点

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }


    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    public void preOrder() {

        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
